/*
 * @lc app=leetcode.cn id=145 lang=javascript
 *
 * [145] 二叉树的后序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function (root) {
  if (root === null) return [];

  const result = [];
  // 双栈，1个保存节点，1个保存压入状态（0：left,1:right,2:print）
  const nodes = [root];
  const status = [0];

  while (nodes.length) {
    // 取出状态
    let s = status.pop();
    switch (s) {
      case 0:
        // 压入左子树，状态改成1
        status.push(1);
        if (nodes[nodes.length - 1].left) {
          nodes.push(nodes[nodes.length - 1].left);
          status.push(0);
        }
        break;
      case 1:
        // 压入左子树，状态改成2
        status.push(2);
        if (nodes[nodes.length - 1].right) {
          nodes.push(nodes[nodes.length - 1].right);
          status.push(0);
        }
        break;
      case 2:
        // 输出值，将节点弹出栈
        result.push(nodes[nodes.length - 1].val);
        nodes.pop();
        break;
    }
  }

  return result;
};
// @lc code=end
